#include "player.h"
#include <QDir>
#include <QDebug>
#include <QObject>
#include<QGraphicsScene>
#include<QTimer>

Player::Player(QObject* parent): QObject(parent), velocityY(0), isGrounded(true), isCrouching(false) {
    loadFrames();

    // 动画定时器（每100ms更新）
    animationTimer.setInterval(100);
    connect (&animationTimer, &QTimer::timeout, this, &Player::updateAnimation);
    animationTimer.start();

    crouchTimer.setInterval(1500);
    connect(&crouchTimer,&QTimer::timeout,this,&Player::resetCrouch);

    setPixmap(runFrames.first());
    adjustPosition();

}

void Player::loadFrames() {
    const int PLAYER_WIDTH=200;
    const int PLAYER_HEIGHT=200;
    // 加载跑动帧
    for(int i = 1;i<=4 ; ++i) {
        QString path = QString(":/images/playerrun%1.png").arg(i%4);
        QPixmap frame(path);

        if(frame.isNull()) {
            if(i == 1) { // 没有找到任何帧
                qCritical() << "No run frames found! Using placeholder.";
                frame = QPixmap(50, 50);
                frame.fill(Qt::blue);
                runFrames << frame;
            }
            break;
        }
        runFrames << frame.scaled(PLAYER_WIDTH, PLAYER_HEIGHT, Qt::KeepAspectRatio,Qt::SmoothTransformation);
    }

    // 加载特殊状态帧
    jumpFrame.load(":/images/playerjump.png");
    if(jumpFrame.isNull()) {
        jumpFrame = QPixmap(50, 50);
        jumpFrame.fill(Qt::darkBlue);
    }
    jumpFrame=jumpFrame.scaled(PLAYER_WIDTH, PLAYER_HEIGHT, Qt::KeepAspectRatio,Qt::SmoothTransformation);
    fallFrame.load(":/images/playerjump.png");
    if(fallFrame.isNull()) {
        fallFrame = QPixmap(50, 50);
        fallFrame.fill(Qt::cyan);
    }
     fallFrame=fallFrame.scaled(PLAYER_WIDTH, PLAYER_HEIGHT, Qt::KeepAspectRatio,Qt::SmoothTransformation);

    crouchFrame.load(":/images/playercrouch.png");
     if(crouchFrame.isNull()){
        crouchFrame=QPixmap(50,30);
         crouchFrame.fill(Qt::yellow);
     }
     crouchFrame=crouchFrame.scaled(PLAYER_WIDTH,PLAYER_HEIGHT,Qt::KeepAspectRatio,Qt::SmoothTransformation);
     // 新增下蹲帧列表
      //crouchFrames << QPixmap(":/res/images/playercrouch1.png").scaled(PLAYER_WIDTH, PLAYER_HEIGHT , Qt::KeepAspectRatio, Qt::SmoothTransformation);
     // crouchFrames << QPixmap(":/res/images/playercrouch2.png").scaled(PLAYER_WIDTH, PLAYER_HEIGHT , Qt::KeepAspectRatio, Qt::SmoothTransformation);
     //  for(int i = 1;i<=2 ; ++i) {
     //     QString path = QString(":/images/playercrouch%1.png").arg(i%2);
     //     QPixmap frame(path);

     //     if(frame.isNull()) {
     //         if(i == 1) { // 没有找到任何帧
     //             qCritical() << "No run frames found! Using placeholder.";
     //             frame = QPixmap(50, 50);
     //             frame.fill(Qt::blue);
     //            crouchFrames << frame;
     //         }
     //         break;
     //     }
     //     crouchFrames << frame.scaled(PLAYER_WIDTH, PLAYER_HEIGHT, Qt::KeepAspectRatio,Qt::SmoothTransformation);
     // }
}

void Player::updateAnimation() {
    switch(currentState) {
    case State::Running:
        currentFrame = (currentFrame + 1) % runFrames.size();
        setPixmap(runFrames[currentFrame]);
        break;
    case State::Jumping:
        setPixmap(jumpFrame);
        break;
    case State::Falling:
        setPixmap(fallFrame);
        break;
    case State::Crouching:
         setPixmap(crouchFrame);
         adjustPosition();
         break;
    }

}

void Player::jump() {
    if(isGrounded&&!isCrouching) {
        velocityY = JUMP_FORCE;
        isGrounded = false;
        setState(State::Jumping);
    }
}

void Player::crouch(){
    if(isGrounded&&currentState !=State::Crouching){
        setState(State::Crouching);
        isCrouching=true;
        crouchTimer.start();
        currentFrame=0;

        // 调试输出
        qDebug() << "Jumping! velocityY: " << velocityY << " isGrounded: " << isGrounded;

    }

}
void Player::resetCrouch(){
    if(isGrounded  &&currentState==State::Crouching){
        setState(State::Running);
        isCrouching=false;
        crouchTimer.stop();
    }
}
void Player::setState(State newState) {
    if(currentState != newState) {
        currentState = newState;
        if(newState == State::Running) {
            currentFrame = 0; // 重置动画帧
        }
    }
}

void Player::updatePhysics() {
    velocityY += GRAVITY;
    setY(y() + velocityY);
    // 调试输出
    qDebug() << "Updating physics: velocityY: " << velocityY << " Y position: " << y();
    // 地面检测
    if(y() + pixmap().height() >= scene()->height()-30) {
        setY(scene()->height() - pixmap().height()-30);
        velocityY = 0;
        isGrounded = true;

        // 调试输出
        qDebug() << "Player grounded! velocityY: " << velocityY << " isGrounded: " << isGrounded;
        if(!isCrouching)setState(State::Running);
    } else {
        setState(velocityY < 0 ? State::Jumping : State::Falling);
    }
    //下蹲时调整碰撞检测高度
    if(currentState==State::Crouching){
        setTransformOriginPoint(boundingRect().center().x(),boundingRect().bottom());
    }
    else{
        setTransformOriginPoint(boundingRect().center());
    }
}
void Player::adjustPosition(){
    if(scene()){
        setPos(x(),scene()->height()-pixmap().height()-30);
    }
}
